﻿using System;
using System.Collections.Generic;
using Opalis.QuickIntegrationKit;
using System.Text;
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;
using System.Collections;

namespace Active_Directory
{
    [OpalisObject("Delete AD Group", ShowFilters = false)]
    class DeleteGroup : IOpalisObject
    {
        private string domainName = string.Empty;
        private string objectName = string.Empty;
        private string objClass = string.Empty;
        private ConnectionCredentials credentials;

        [OpalisConfiguration]
        public ConnectionCredentials Credentials
        {
            get { return credentials; }
            set { credentials = value; }
        }

        public void Design(IOpalisDesigner designer)
        {
            designer.AddInput("Group LDAP Path").WithDefaultValue("LDAP://cn=GroupName,ou=Container,DC=Contoso,DC=Com");
            designer.AddOutput("Group LDAP Path").AsString();
        }

        public void Execute(IOpalisRequest request, IOpalisResponse response)
        {
            string groupDn = request.Inputs["Group LDAP Path"].AsString();
            
            if (DirectoryEntry.Exists(groupDn))
            {
                try
                {
                    String GroupName = groupDn.Split(',')[0];
                    
                    DirectoryEntry group = new DirectoryEntry(groupDn, credentials.UserName + "@" + credentials.Domain, credentials.Password);
                    DirectoryEntry parent = new DirectoryEntry("LDAP://" + groupDn.Substring(GroupName.Length + 1), credentials.UserName + "@" + credentials.Domain, credentials.Password);
                    parent.Children.Remove(group);
                    parent.CommitChanges();
                    response.Publish("Group LDAP Path", groupDn);
                }
                catch (System.DirectoryServices.DirectoryServicesCOMException E)
                {
                    response.LogErrorMessage(E.Message.ToString());
                }
            }
            else
            {
                response.LogErrorMessage("Group with DN " + groupDn + " does not exist");
            }
        }
    }
}
